package org.xxpay.pay.channel;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.entity.PayPassageAccount;
import org.xxpay.pay.util.Util;

/**
 * @author: dingzhiwei
 * @date: 17/12/24
 * @description:
 */
@Component
public abstract class BasePayment extends BaseService implements PaymentInterface {

    /** 当前线程变量，用于判断当前是否是测试状态
     由于getPayParam()函数中判断了子账号的状态, 当X新增后状态是非开启，也需要进行接口验证，所以添加该线程变量；
     另外商户下单时前置判断条件已经验证了该账号状态，此时判断状态感觉有点重复（需确认）；
     **/
    public static final ThreadLocal<String> IS_TEST_FLAG = new ThreadLocal<>();

    public abstract String getChannelName();

    public String getOrderId(PayOrder payOrder) {
        return null;
    }

    public Long getAmount(PayOrder payOrder) {
        return null;
    }

    public AbstractRes pay(PayOrder payOrder) {
        return null;
    }

    public QueryRetMsg query(PayOrder payOrder) {
        return null;
    }

    public JSONObject close(PayOrder payOrder) {
        return null;
    }

    /**
     * 获取三方支付配置信息
     * 如果是平台账户,则使用平台对应的配置,否则使用商户自己配置的渠道
     * @param payOrder
     * @return
     */
    public String getPayParam(PayOrder payOrder) {
        String payParam = "";
        PayPassageAccount payPassageAccount = commonService.payPassageAccountService.findById(payOrder.getPassageAccountId());

        if(payPassageAccount == null) throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST);
        if(StringUtils.isBlank(IS_TEST_FLAG.get()) && payPassageAccount.getStatus() != MchConstant.PUB_YES){ // 空=非测试，需要判断状态是否开启
            throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST);
        }

        payParam = payPassageAccount.getParam();
        if(StringUtils.isBlank(payParam)) throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST); //仍然为空，说明配置有误

        return payParam;
    }


    /** 统一生成二维码图片地址,  大小：200*200 **/
    protected String genCodeImgUrl(String codeUrl){
        return getDBApplicationConfig().getConfig4PayUrl() + "/qrcode_img_get?url=" + codeUrl + "&width=200&height=200";
    }

    /**
     * 获取客户请求IP，如果订单中没有则返回随机IP
     * @param payOrder
     * @return
     */
    protected String getClientIp(PayOrder payOrder) {
        String clientIp = payOrder.getClientIp();
        if(StringUtils.isBlank(clientIp)) return Util.getRandomIp();
        return clientIp;
    }

}
